﻿#pragma once
#include "LuaCommon.h"
#include "LuaState.h"

class LuaObjectImpl
{
public:
	//创建
	static LuaObjectImpl* createFromIndex(LuaState* L,int idx);
	static inline LuaObjectImpl* createFromTop(LuaState* L) {
		return createFromIndex(L, -1);
	}

	//nil
	static LuaObjectImpl* create(LuaState* L);

	//number
	static LuaObjectImpl* create(LuaState* L,lua_Integer num);

	static LuaObjectImpl* create(LuaState* L,lua_Number num);

	//string
	static LuaObjectImpl* create(LuaState* L,const char* str,int len=-1);

	//bool
	static LuaObjectImpl* create(LuaState* L,bool b);

	static LuaObjectImpl* create(LuaState* L,void* ptr);


	static int callDelegate(lua_State* L);

	static LuaObjectImpl* create(LuaState* L,LuaCFunction f);


	static LuaObjectImpl* createData(LuaState* L,void* ud,size_t len);

	static LuaObjectImpl* createData(LuaState* L,size_t len);

	static LuaObjectImpl* createTable(LuaState* L,int arrSize,int hashSize);

    static LuaObjectImpl* createThread(LuaState* L);

	//从全局进行初始化
	static LuaObjectImpl* createGetGlobal(LuaState* L,const char* name);

	static LuaObjectImpl* createGetRegistery(LuaState* L,const char* key);

	static LuaObjectImpl* createGetRegistery(LuaState* L,int key);

	static LuaObjectImpl* createGetRegistery(LuaState* L,void* key);	


	//释放
	void free();

	inline int addRef(){
		return ++m_ref;
	}

	inline int release(){
		int count = --m_ref;
		if (!count) {
			free();
		}
		return count;
	}

	inline int getRef()const{
		return m_ref;
	}

	inline int getIndex()const{
		return m_index;
	}

	inline LuaState* getCppLuaState(){
		return m_ls;
	}

	inline lua_State* getLuaState(){
		return m_ls->getLuaState();
	}

	inline LuaState*  getLuaThread() {
		return m_thread; 
	}

	inline void copyToTop() {
		lua_pushvalue(getLuaState(), m_index);
	}
private:
	friend class LuaState;
	LuaState* m_ls;
    LuaState* m_thread;
	int m_ref;
	int m_index;//-1表示未初始化
	LuaObjectImpl* m_prev;
	LuaObjectImpl* m_next;
};



